package ie.dcu.spca;

import java.util.HashMap;
import java.util.Map;

import ie.dcu.spca.data.DataManager;
import ie.dcu.spca.data.db.DBDataManager;
import ie.dcu.spca.view.bill.BillList;
import ie.dcu.spca.view.category.CategoryList;
import ie.dcu.spca.view.product.ProductList;
import ie.dcu.spca.view.user.UserList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Process;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class Main extends Activity {

    public static DataManager dataManager;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        init();
    }

    /**
     * Initialize the DataManager and buttons
     */
    private void init() {
        // So important
        if (dataManager == null) {
            dataManager = new DBDataManager(this);
            dataManager.open();
        }

        buttonIdActivityClassMap.put(R.id.gotoUserButton, UserList.class);
        buttonIdActivityClassMap.put(R.id.gotoCategoryButton,
                CategoryList.class);
        buttonIdActivityClassMap.put(R.id.gotoProductButton, ProductList.class);
        buttonIdActivityClassMap.put(R.id.gotoBillButton, BillList.class);

        for (Integer i : buttonIdActivityClassMap.keySet())
            bindGotoNextPage(i);

        ((Button) findViewById(R.id.cancelOptButton))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        destoryTheProgram();
                    }
                });
        ((Button) findViewById(R.id.sendDBOptButton))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendDb();
                    }
                });
    }

    private void destoryTheProgram() {
        Main.dataManager.close();
        Main.this.finish();
        Process.killProcess(Process.myPid());
    }

    private Map<Integer, Class> buttonIdActivityClassMap = new HashMap<Integer, Class>();

    private void bindGotoNextPage(int buttonId) {
        // Manager Button Event
        ((Button) findViewById(buttonId))
                .setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent nextPageIntent = new Intent();
                        nextPageIntent.setClass(Main.this,
                                buttonIdActivityClassMap.get(v.getId()));
                        startActivity(nextPageIntent);
                    }
                });
    }

    private void sendDb() {
        dataManager.sendDB();
    }
}
